#include <stdlib.h>
#include "spectrum.h"
#include "rc.h"

uint8_t SpektrumTimer;

/*
Code derived from:

Copyright (c) Rainer Walther
RC-routines from original MK rc.c (c) H&I
Useful infos from Walter: http://www.rcgroups.com/forums/showthread.php?t=714299&page=2
only for non-profit use

Connection of Spectrum Sattelite to SV1 of FC:

Orange:		3V from the FC (never connect 5V!)
Black:		GND
Gray:		RXD1 (Pin 3)

If a receiver is connected via PPM input at the same time, the PPM input will be disabled
if a stable signal can be captured by the uart.

Data are send at every 20 ms @ 115200 Baud 8-N-1

DX7/DX6i: One data-frame @ 115200 Baud 8-N-1 every 22ms.
DX7se:    One data-frame @ 115200 Baud 8-N-1 every 11ms.

Frame consist of:
byte1:  unknown
byte2:  unknown
byte3:  and byte4:  channel data
byte5:  and byte6:  channel data
byte7:  and byte8:  channel data
byte9:  and byte10: channel data
byte11: and byte12: channel data
byte13: and byte14: channel data
byte15: and byte16: channel data

DS9 (9 Channel): One data-frame @ 115200 Baud 8-N-1 every 11ms,
alternating frame 1/2 for CH1-7 / CH8-9

1st Frame consist of:
byte1:  unknown
byte2:  unknown
byte3:  and byte4:  channel data
byte5:  and byte6:  channel data
byte7:  and byte8:  channel data
byte9:  and byte10: channel data
byte11: and byte12: channel data
byte13: and byte14: channel data
byte15: and byte16: channel data

2nd Frame consist of:
byte1:  unknown
byte2:  unknown
byte3:  and byte4:  channel data
byte5:  and byte6:  channel data
byte7:  and byte8:  0xffff
byte9:  and byte10: 0xffff
byte11: and byte12: 0xffff
byte13: and byte14: 0xffff
byte15: and byte16: 0xffff

Each channel data (16 bit = 2byte, first msb, second lsb) is arranged as:

Bits: F 0 C3 C2 C1 C0 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0

0 means a '0' bit
F: 0 = indicate first frame, 1 = indicates beginning of 2nd frame for CH8-9 (DS9 only)
C3 to C0 is the channel number. 0 to 9 (4 bit, as assigned in the transmitter)
D9 to D0 is the channel data (10 bit) 0xaa..0x200..0x356 for 100% transmitter-travel
*/

#define MIN_FRAMEGAP 68  // 7ms
#define MAX_BYTEGAP  3   // 375us

void spectrum_parser(uint8_t c)
{
	static uint8_t Sync = 0, FrameCnt = 0, ByteHigh = 0, ReSync = 1, Frame2 = 0;
	uint16_t Channel, index;
	int16_t signal; //tmp;
	int16_t bCheckDelay;


	if (ReSync == 1)
	{
		// wait for beginning of new frame
		ReSync = 0;
		SpektrumTimer = MIN_FRAMEGAP;
		FrameCnt = 0;
		Sync = 0;
		ByteHigh = 0;
	}
	else
	{
		if(!SpektrumTimer) bCheckDelay = 1;
		else               bCheckDelay = 0;
		if ( Sync == 0 )
	    {
			if(bCheckDelay)
		    {
				// nach einer Pause von mind. 7ms erstes Sync-Character gefunden
				// Zeichen ignorieren, da Bedeutung unbekannt
				SpektrumTimer = MAX_BYTEGAP;
				FrameCnt++;
				Sync = 1;
			}
			else
			{
				// Zeichen kam vor Ablauf der 7ms Sync-Pause
				// warten auf erstes Sync-Zeichen
				SpektrumTimer = MIN_FRAMEGAP;
				FrameCnt = 0;
				Sync = 0;
				ByteHigh = 0;
			}
		}
		else if((Sync == 1) && !bCheckDelay)
	    {
			// zweites Sync-Character ignorieren, Bedeutung unbekannt
			SpektrumTimer = MAX_BYTEGAP;
			Sync = 2;
			FrameCnt++;
		}
		else if((Sync == 2) && !bCheckDelay)
	    {
			// Datenbyte high
			SpektrumTimer = MAX_BYTEGAP;
			ByteHigh = c;
			if (FrameCnt == 2)
		    {
				// is 1st Byte of Channel-data
				// Frame 1 with Channel 1-7 comming next
				Frame2 = 0;
				if(ByteHigh & 0x80)
			    {
					// DS9: Frame 2 with Channel 8-9 comming next
					Frame2 = 1;
				}
			}
			Sync = 3;
			FrameCnt ++;
		}
		else if((Sync == 3) && !bCheckDelay)
	    {
			// Datenbyte low
			// High-Byte for next channel comes next
			SpektrumTimer = MAX_BYTEGAP;
			Sync = 2;
			FrameCnt ++;
			index = (ByteHigh >> 2) & 0x0f;
			index ++;
			Channel = ((uint16_t)ByteHigh << 8) | c;
			signal = Channel & 0x3ff;
			signal -= 0x200;		// Offset, range 0x000..0x3ff?
			signal = signal/3;		// scaling to fit PPM resolution

			if(index >= 0  &&  index < MAX_CHANNELS)
			{
				if(RC_Channels < index)  RC_Channels = index;
				// Stabiles Signal
				if(abs(signal - PPM_in[index]) < 6)
				{
					if(RC_Quality < 200)
					{
						RC_Quality += 10;
					}
					else
					{
						RC_Quality = 200;
						PPM_INPUT_OFF; // disable PPM input at ICP
					}
				}
				//tmp = (3 * PPM_in[index] + signal)/4;
				//if(tmp > signal+1) tmp--;
				//else if(tmp < signal-1) tmp++;
				// calculate signal difference on good signal level
				if(RC_Quality >= 180)  PPM_diff[index] = ((signal - PPM_in[index]) / 3) * 3;
				else PPM_diff[index] = 0;
				PPM_in[index] = signal;
			}
			else if(index > 17) ReSync = 1; // hier stimmt was nicht: neu synchronisieren
		}
		else
		{
			// hier stimmt was nicht: neu synchronisieren
			SpektrumTimer = MIN_FRAMEGAP; // next frame expexted after 7ms
			ReSync = 1;
			FrameCnt = 0;
			Frame2 = 0;
		}

		// 16 Bytes per frame --> frame complete
		if(FrameCnt >= 16)
		{
			// Frame complete
			if(Frame2 == 0)
			{
				// Null bedeutet: Neue Daten
				// nur beim ersten Frame (CH 0-7) setzen
				if(!ReSync) NewPpmData = 0;
			}
			SpektrumTimer = MIN_FRAMEGAP;
			FrameCnt = 0;
			Frame2 = 0;
			Sync = 0;
		}
	}
}

